package com.jiangdg.demo

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.jiangdg.ausbc.utils.ToastUtils
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class FileGroupAdapter(private val context: Context, private var fileGroups: List<FileGroup> = mutableListOf(),val itemSelectListener: OnItemSelectListener) :
    RecyclerView.Adapter<FileGroupAdapter.FileGroupViewHolder>() {
    var editMode :Boolean = false
    private val selectedItems = mutableSetOf<File>()

    inner class FileGroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val dateTextView: TextView = itemView.findViewById(R.id.date_text_view)
        val filesRecyclerView: RecyclerView = itemView.findViewById(R.id.files_recycler_view)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileGroupViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.file_group_item_layout, parent, false)
        return FileGroupViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: FileGroupViewHolder, position: Int) {
        val fileGroup = fileGroups[position]
        holder.dateTextView.text = fileGroup.date

        holder.filesRecyclerView.layoutManager = GridLayoutManager(context, 4)
        holder.filesRecyclerView.adapter = FileAdapter(context, fileGroup.files,this)
    }

    override fun getItemCount(): Int {
        return fileGroups.size
    }

    fun setData(list: List<FileGroup>){
        fileGroups = list
        notifyDataSetChanged()
    }

    fun onPicLongClick(){
        editMode = true
        itemSelectListener.onEditModelChange(editMode)
        notifyDataSetChanged()
    }

    fun toggleModel(){
        editMode = false
        itemSelectListener.onEditModelChange(editMode)
        notifyDataSetChanged()
    }


    fun deleteSelectedItems() {
        selectedItems.forEach {
            val delete = it.deleteRecursively()
            if (delete){
                for (fileGroup in fileGroups) {
                    fileGroup.files.remove(it)
                }
            }
        }
        selectedItems.clear()
        notifyDataSetChanged()
    }

    fun saveAllSelected(){
        selectedItems.forEach {
            if (isPic(it)){
                ImageSaver.saveImageToGallery(context,it.path)
            }else{
                ImageSaver.saveMp4ToGallery(context,it.path)
            }
        }
        ToastUtils.show(R.string.text_0020)
    }

    class FileAdapter(private val context: Context, private val files: List<File>,val fileGroupAdapter: FileGroupAdapter) :
        RecyclerView.Adapter<FileAdapter.FileViewHolder>() {


        inner class FileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val fileImageView: ImageView = itemView.findViewById(R.id.thumbnail_image)
            val ivType: ImageView = itemView.findViewById(R.id.ivType)
            val tvTime: TextView = itemView.findViewById(R.id.tvTime)
            val ivCheck: ImageView = itemView.findViewById(R.id.ivCheck)
            val ivDownload: ImageView = itemView.findViewById(R.id.ivDownload)

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
            val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.thumbnail_item_layout, parent, false)
            itemView.setOnLongClickListener {
                fileGroupAdapter.onPicLongClick()
                true
            }
            return FileViewHolder(itemView)
        }

        override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
            val file = files[position]
            CoroutineScope(Dispatchers.Main).launch {
                Glide.with(context)
                    .load(MediaCache.getMediaFrame(file.absolutePath,context))
                    .transition(DrawableTransitionOptions.withCrossFade()) // Add cross-fade transition
                    .apply(RequestOptions().transform(CenterCrop(), RoundedCornersTransformation(20, 0)))
                    .into(holder.fileImageView)
            }
            holder.ivDownload.setOnClickListener {
                if (fileGroupAdapter.isPic(file)){
                    ImageSaver.saveImageToGallery(context,file.path)
                }else{
                    ImageSaver.saveMp4ToGallery(context,file.path)
                }
            }
            holder.itemView.setOnClickListener {v->
                if (!fileGroupAdapter.editMode){
                    CoroutineScope(Dispatchers.Main).launch {
                        val mutableList:MutableList<String> = mutableListOf()
                        var currentPosition = 0
                        var index = 0
                        files.forEach {
                            if (fileGroupAdapter.isPic(it)){
                                mutableList.add(it.path)
                                if (it.path.equals(file.path)){
                                    currentPosition = index
                                }
                            }
                            index++
                        }
                        val  intent = ImagePreviewActivity.createIntent(context, ArrayList(mutableList),currentPosition)
                        context.startActivity(intent)
                    }
                }else{
                    //选择
                    if (fileGroupAdapter.selectedItems.contains(file)) {
                        fileGroupAdapter.selectedItems.remove(file)
                    }else{
                        fileGroupAdapter.selectedItems.add(file)
                    }
                    notifyItemChanged(position)
                }
            }
            holder.ivCheck.setImageResource(if (fileGroupAdapter.selectedItems.contains(file)) R.drawable.icon_round_select else R.drawable.icon_round_un_select)
            holder.ivCheck.visibility = if (fileGroupAdapter.editMode) View.VISIBLE else View.GONE
            holder.ivType.setImageResource(if (fileGroupAdapter.isPic(file))  R.mipmap.icon_pic else R.mipmap.icon_mp4)
            holder.tvTime.visibility = View.VISIBLE
            holder.tvTime.text = FileUtil.formatFileLastModified(file,"HH:mm:ss")
        }

        override fun getItemCount(): Int {
            return files.size
        }
    }


    private fun isMp4(file: File):Boolean{
        return file.isFile && (file.extension.equals("mp4", ignoreCase = true) || file.extension.equals("avi", ignoreCase = true) || file.extension.equals("mkv", ignoreCase = true))
    }

    private fun isPic(file: File):Boolean{
        return file.extension.equals("jpg", ignoreCase = true) || file.extension.equals("jpeg", ignoreCase = true) || file.extension.equals("png", ignoreCase = true)
    }

    interface OnItemSelectListener{
        fun onEditModelChange(file: Boolean)
    }
}
